/**
 * @desc 在实际开发中，您可以将 baseUrl 替换为您的请求地址前缀；
 *
 * 已将 $apis 挂载在 global，您可以通过如下方式，进行调用：
 * $apis.example.getApi().then().catch().finally()
 *
 * 备注：如果您不需要发起请求，删除 apis 目录，以及 app.ux 中引用即可；
 */
import config from '../../config.js';
const baseUrl =config.url;
let util='';

 function 	getBaseUrl(head=false) {
		if ( util.isdebug()) {
			return baseUrl;
		}
		let _base_url = baseUrl;
		// #ifdef H5
			_base_url =(head?window.location.protocol:"")+'//' + window.location.host;
		// #endif
		return _base_url;
	}
	function responseHandle(res) {
		res = res.data;
		if (res.code != 200) {
			// wrong handle
			switch (res.code) {
				case 401: //未登录
					 util.login();
					break;
				default:
					 util.util_toast( (res.code + (res.message || res.msg)));
					console.log(res)
					break;
			}
		}
		return res.code != 200;
	}
	function request_err(err) {
		console.log(`🐛 request fail, err = ${err}`+JSON.stringify(err))
	}

	function  _post(url, data, cb = "", ca = "") {
		//let path =  getBaseUrl() +'/api/'+ url;
		 let path =  getBaseUrl() + url;
		uni.request({
			url: path,
			method: 'POST',
			data: data,
			header:make_header(data),
			success: (res) => {
				 responseHandle(res) ? ca(res.data.message) : cb(res.data.data)
			},
			fail:  request_err
		});
	}
function make_header(data = null) {
		if (!data) data = {};
		let header = data.header || {
			'Content-Type': 'application/json;charset=UTF-8'
		};
		let token =  util.getToken()
		let generalize =  util.getGeneralize()
		let share_id =  util.getShareId()
		let rid =  util.getRid();
		let source =  util.getSenceType();
		if(source) header.source = source;
		if (token) header.Authorization = 'Bearer ' + token; //请求头加上token // 判断是否存在token，如果存在的话，则每个http header都加上token
		if (generalize) header.Generalize = generalize;
		if(share_id) header.share_uid = share_id;
		if(rid &&  util.isPreLoginMode())header.meid = rid;
		// console.log("api isPreLoginMode: ",util.isPreLoginMode(),JSON.stringify(header))
		return header;
	}

	 function _get(url, data = '', cb = '', ca = '') {
		console.log('api _get: ',url)
		// let path =  getBaseUrl() +'/api/'+ url;
		  let path =  getBaseUrl() + url;
		  
		uni.request({
			url: path,
			method: 'GET',
			data: data,
			header:  make_header(data),
			success: (res) => {
				 responseHandle(res) ? ca(res.data.message) : cb(res.data.data)
			},
			fail:  request_err
		});
	}
  
	 function _text(url, data = '', header = '', cb = '', ca = '') {
		let path = (url.indexOf('http') == 0) ? url :  getBaseUrl() + url;
		uni.request({
			url: path,
			method: 'GET',
			data: data,
			header: header,
			dataType: 'text',
			success: cb,
			fail:  request_err
		});
	}
	
export default {
	setUtil(ut){
		console.log('setUtil')
		util=ut;
	},
	getAuthorUrl() {
		return  getBaseUrl(true) + '/auth';
	},
	getBaseUrl,
	changeGuess(anid = 1, cb = '', ca = '') {
		 _post('/busiapi/bookstores/change_guess', {
			anid: 1
		}, cb, ca);
	},
	getAnimaInfo(anid, cb, ca) {
		 _get('/busiapi/bookstores/anime_info', {
			anid: anid
		}, cb, ca);
	},
	chapterList(anid, cb, ca) {
		 _post('/busiapi/bookstores/chapter', {
			anid: anid
		}, cb, ca)
	},
	lastRead(anid='', cb, ca) {
		 _get('/busiapi/bookstores/anime_last_history', {
			anid: anid
		}, cb, ca);
	},

	getRankTreeData(cb = '', ca = '') {
		 _get('/busiapi/web/rank', '', cb, ca)
	},
	getCloumnBooks: (page, pageSize, columId, cb = '', ca = '') => {
		console.log('getCloumnBooks',this);
		 _post('/busiapi/web/rank_search', {
			page: page,
			pageSize: pageSize,
			columId: columId
		}, cb, ca);
	},
	freeBooks(page, pageSize, sex,cb, ca = '') {
		 _get('/busiapi/bookstores/free', {
			page: page,
			sex:sex,
			pageSize: pageSize
		}, cb, ca)
	},
	serailBooks(page, pageSize, sex,cb, ca = '') {
		 _get('/busiapi/bookstores/serial', {
			page: page,
			sex:sex,
			pageSize: pageSize
		}, cb, ca)
	},
	
	longBooks(page, pageSize,sex, cb, ca = ''){ 
			_get('/busiapi/bookstores/long', {
				page: page,
				sex:sex,
				pageSize: pageSize
			}, cb, ca)
		},
	shortBooks(page, pageSize, sex,cb, ca = ''){
		_get('/busiapi/bookstores/short', {
				page: page,
				sex:sex,
				pageSize: pageSize
			}, cb, ca)
		
	},
	
	finishedBooks(page, pageSize, sex,cb, ca = '') {
		 _get('/busiapi/bookstores/finished', {
			page: page,
			sex:sex,
			pageSize: pageSize
		}, cb, ca);
	},
	clearRecord(cb, ca) {
		 _post('/busiapi/bookstores/empty_read_history', null, cb, ca);
	},
	addBookshelfs(anid, cb, ca) {
		 _get('/busiapi/bookstores/add_to_shelve', {
			anid: anid
		}, cb, ca)
	},
	addToHistory(anid, chaps, cb, ca) {
		 _post('/busiapi/bookstores/add_read_history', {
			anid: anid,
			chaps: chaps
		}, cb, ca);
	},
	getReadRecords(page, pageSize, cb, ca) {
		 _get('/busiapi/bookstores/read_history', {
			page: page,
			page_size: pageSize
		}, cb, ca);
	},
	readBook(anid, chapter, cb, ca) {
		 _post('/busiapi/bookstores/read', {
			anid: anid,
			chaps: chapter,
		}, cb, ca);
	},
	deleteBookRecords(anid, cb, ca) {
		 _get('/busiapi/bookstores/delete_read_history', {
			id: anid
		}, cb, ca);
	},
	
	
	getBookshelf(page, page_size, sort, cb, ca) {
		 _get('/busiapi/bookstores/shelf', {
			page: page,
			page_size: page_size,
			sort: sort,
		}, cb, ca);
	},
	removeBookshelf(id, cb, ca) {
		 _get('/busiapi/bookstores/remove_from_shelve', {
			id: id,
		}, cb, ca);
	},
	
	libarSearch(searchs, cb, ca) {
		 _post('/busiapi/web/libr_search', searchs, cb, ca);
	},
	libarList(cb, ca) {
		 _get('/busiapi/web/libr', null, cb, ca);
	},
	
	
	pay_chapter(anid, chaps, code,cb, ca) {
		 _post('/busiapi/bookstores/pay_chapter', {
			anid: anid,
			chaps: chaps,
			code:code||"",
		}, cb, ca)
	},
	pay_chapter_by_reward(anid, chaps,code, cb, ca) {
		 _post('/busiapi/bookstores/pay_chapter', {
			anid: anid,
			chaps: chaps,
			code:code||"",
			type:'reward',
		}, cb, ca)
	},
	
	count_read_time(time_send, params,cb, ca) {
		 _get('/busiapi/bookstores/count_read_time', {
			time: time_send,
			...params
		}, cb, ca);
	},
	channelList(cb, ca) {
		 _get('/busiapi/bookstores/channel', null, cb, ca);
	},
	channelData(channel_id, page, page_size, cb, ca) {
		 _get('/busiapi/bookstores/channel_data', {
			channel_id: channel_id,
			p: page,
			page_size: page_size
		}, cb, ca)
	},
	more(params, cb, ca) {
		 _get('/busiapi/bookstores/get_anime_by_channel', params, cb, ca);
	},
	upWriterApplyWithPath(data,cb,ca){
		 _post('/busiapi/user/writer_apply',data,cb,ca);
		
	},
	upWriterApply(files, data, cb, ca) {
		uni.uploadFile({
			url:  getBaseUrl() + '/busiapi/user/writer_apply',
			header:  make_header(data),
			files: files,
			formData: data,
			success: (res) => {
				console.log('handling success' + JSON.stringify(res))
				cb(res)
			},
			fail: (err) => {
				console.log(`handling fail,` + JSON.stringify(err))
				ca(err);
			}
		})
	},
	
	
	
	
	logout(cb, ca = '') {
		 _post('/api/logout', null, cb, ca);
	},
	
	
	getOpenId(data, cb, ca) { // 通过code获取 openId等用户信息，/api/user/wechat/login 为后台接口
		 _post('/api/wechat_official_account_login', data, cb, ca)
	},
	upLoadFile(file, then, catche) {

	},
	
	addUserAccount(account_info, cb, ca = '') {
		 _post('/api/user_account', account_info, cb, ca)
	},
	unbindThird(type, cb, ca) {
		 _post('/api/unbind_third', {
			type: type,
		}, cb, ca)
	},
	getbindInfo(cb, ca) {
		 _post('/api/get_bind_info', null, cb, ca)
	},

	
	userinfo(cb, ca) {
		 _get('/api/user_info', null, cb, ca);
	},
	userBaseinfo(cb, ca) {
		 _post('/api/user/base_info', null, cb, ca);
	},
	getHobby(cb, ca) {
		 _post('/api/user/hobby', null, cb, ca)
	},
	
	setHobby(issex, cids, cb, ca) {
		 _post('/api/user/save_hobby', {
			issex: issex,
			cids: cids,
		}, cb, ca);
	},
	wxjssdk(url, cb, ca) {
		 _post('/api/wechat/jssdk', {
			url: url
		}, cb, ca)
	},
	getUserBaseInfo(cb, ca) {
		 _get('/api/user_info', null, cb, ca)
	},

	takeKisengCode(anid,cb,ca){
		_post('/busiapi/kocps/ks_apply',{
			anid:anid
		},cb,ca);
	},



	getWithdrawList(page, pageSize, cb, ca) {
		 _post('/api/withdraw/logs', {
			page: page,
			page_size: pageSize,
		}, cb, ca);
	},
	getWithdrawDetail(id, cb, ca) {
		 _post('/api/withdraw/detail', {
			id: id
		}, cb, ca);
	},
	delMessage(id, type, cb, ca) {
		 _post('/api/message/delete', {
			id: id,
			type: type,
		}, cb, ca);
	},
	getMessageList(cat_type, type, page, page_size, cb, ca) {
		 _post('/api/message/index', {
			cat_type: cat_type,
			type: type,
			page: page,
			page_size: page_size,
		}, cb, ca);
	},
	readMessage(id, type, cb, ca) {
		 _post('/api/message/reading', {
			id: id,
			type: type,
		}, cb, ca);
	},
	rechangeBaseInfo(cb, ca) {
		_get('/api/charge/base_info', null, cb, ca);
	},
	rechangeTotalInfo(cb, ca) {
		_get('/api/charge/total_info', null, cb, ca);
	},
	witchdrawBaseInfo(cb, ca) {
		_get('/api/withdraw/base_info', null, cb, ca);
	},
	witchdraw(account,real_name,amount,cb, ca) {
		_post('/api/withdraw/at_once', {
			account:account,
			real_name:real_name,
			amount:amount,
		}, cb, ca);
	},


	createPayOrder(charge_id, pay_type, scene, anid, chap, return_url, cb, ca) {
		this.createPayOrderWithData({
			charge_id: charge_id,
			pay_type: pay_type,
			scene: scene,
			//  scene_type: scene_type,
			anid: anid,
			chap: chap,
			return_url: return_url
		}, cb, ca);
	},
	createPayOrderWithData(params, cb, ca) {
		_post('/api/charge/create_order', params, cb, ca);
	},
	createVipPayOrderWithData(params, cb, ca) {
		 _post('/api/vip/create_order', params, cb, ca);
	},
	saveAvatar(avatar, cb, ca) {
		 _post('/api/save_avatar', {
			avatar: avatar
		}, cb, ca);
	},
	saveNickName(nickname, cb, ca) {
		 _post('/api/save_nickname', {
			nickname: nickname
		}, cb, ca);
	},
	saveGender(gender, cb, ca) {
		 _post('/api/save_gender', {
			gender: gender
		}, cb, ca);
	},
	vipBaseinfo(cb, ca) {
		 _post('/api/vip/base_info', null, cb, ca)
	},
	withdrawalBaseinfo(page, pageSize, cb, ca) {
		 _get('/api/withdraw/base_info', {
			page: page,
			page_size: pageSize,
		}, cb, ca)
	},
	
	financelist(page, pageSize, cb, ca) {
		 _get('/api/withdraw/finance_list', {
			page: page,
			page_size: pageSize,
		}, cb, ca)
	},
	
	getWidthdrawIndex(cb, ca) {
		 _get('/api/withdraw/index', null, cb, ca)
	},
	getUserAccountList(cb, ca) {
		 _get('/api/user_account', null, cb, ca);
	},
	welfareCheckin(coin, cb, ca) {
		 _post('/api/welfare/sign', {
			coin: coin
		}, cb, ca);
	},
	welfareBaseInfo(cb, ca) {
		 _get('/api/welfare/base_info', null, cb, ca)
	},
	getWriterApply(uid, cb, ca) {
		 _post('/api/user/get_writer_apply', {
			uid: uid
		}, cb, ca);
	},
	complaint(type,txt,cb,ca){
		_post('/api/user/complaint', {
			type: type,
			txt:txt,
		}, cb, ca);
	},
	
	
	search(keyword, page, page_size, cb, ca) {
		 _post('/api/search/index', {
			keyword: keyword,
			page: page,
			page_size: page_size,
		}, cb, ca);
	},
	searchBaseinfo(cb, ca) {
		 _get('/api/search/base_info', null, cb, ca);
	},
	
	
	is_subcribe_wechat_mp(cb, ca) {
		 _post('/api/user/is_subscribe_wechat_mp', null, cb, ca);
	},
	subcribe_wechat_mp(scene, scene_data, cb, ca) {
		 _post('/api/user/wechat_subscribe_qrcode', {
			scene: scene,
			scene_data: scene_data
		}, cb, ca);
	},
	logOff(cb,ca=''){
		 _post('/api/logoff',null,cb,ca);
	},
	pwdLogin(phone, pwd, cb, ca) {
		 _post('/api/pwd_login', {
			phone: phone,
			password: pwd,
		}, cb, ca);
	},
	quickLogin(data, cb, ca) {
		 _post("/api/quick_login", data, cb, ca);
	},
	pwdRegister(data, cb, ca) {
		 _post('/api/register', data, cb, ca);
	},
	restPwd(data, cb, ca) {
		 _post('/api/reset_pwd', data, cb, ca);
	},
	
	
	customProblem(cb, ca) {
		 _get('/user/contact', null, cb, ca);
	},
	
	getInviteRules(uid, cb, ca) {
		 _get('/invite/rule', {
			params: {
				uid: uid,
			}
		}, cb, ca);
	},
	
	getIllustrationContent(mark, cb, ca) {
		 _get('/illustration/index', {
			mark: mark
		}, cb, ca);
	},
	
	uploadFile(filePath, data, cb, ca){
		uni.uploadFile({
			url:  getBaseUrl() + '/common/upload_file',
			header:  make_header(data),
			filePath:filePath,
			name:'targetFile',
			success: (res) => {
				res.data=JSON.parse(res.data);
				cb(res.data)
			},
			fail: (err) => {
				console.log(`handling fail,` + JSON.stringify(err))
				ca(err);
			}
		})
	},
	appInit(cb = '', ca = '') {
		console.log('api appinit', util, util.isdebug);;
		 _post('/common/appinit', null, cb, ca);
	},
	rewardInfo(cb,ca){
		 _get('/common/reward_info', null, cb, ca);
	},
	sendSms(mobile, type, cb, ca = '') {
		 _post("/common/sms_send", {
			mobile: mobile,
			type: type,
		}, cb, ca)
	},
	errlog(err, cb, ca = '') {
		 _post("/common/errlog", {
			err:err
		}, cb, ca)
	},
	text(url,cb,ca){
		return _text(url,{},{},cb,ca)
	}
}
